package com.cgl.controller;

import com.auth0.jwt.interfaces.Claim;
import com.cgl.pojo.Result;
import com.cgl.pojo.User;
import com.cgl.service.UserService;
import com.cgl.until.EmailSender;
import com.cgl.until.JwtUntil;
import jakarta.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.net.http.HttpRequest;
import java.util.HashMap;
import java.util.Map;

@RestController
public class UserCcontroller {
    private static final Logger logger = LoggerFactory.getLogger(UserCcontroller.class);
    private static final HashMap<String,String> codeMap = new HashMap<>();
    @Autowired
    private UserService userService;
    @PostMapping("login")
    public Result login(@RequestBody User user){
        logger.info("用户登录:{}", user);
        if (user.getEmail() == null || user.getEmail().equals("")){
            return Result.error("邮箱不能为空");
        }
        //验证邮箱格式
        else if (!user.getEmail().matches("^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+)+$")){
            return Result.error("邮箱格式错误");
        }
        else if (user.getPassword() == null || user.getPassword().equals("")){
            return Result.error("密码不能为空");
        }
        User user1 = userService.login(user);
        if (user1 != null){
            String  Jwt= JwtUntil.createToken("userId",user1.getId());

            user1.setToken(Jwt);

            return Result.success(user1);
        }
        else {
            return Result.error("用户名或密码错误");
        }
    }

    @PostMapping("register")
    public Result register(@RequestBody User user){
        logger.info("用户注册:{}", user);
        if (user.getEmail() == null || user.getEmail().equals("")){
            return Result.error("邮箱不能为空");
        }
        //验证邮箱格式
        else if (!user.getEmail().matches("^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+)+$")){
            return Result.error("邮箱格式错误");
        }
        else if (user.getUsername() == null || user.getUsername().equals("")){
            return Result.error("用户名不能为空");
        }
        else if (user.getPassword() == null || user.getPassword().equals("")){
            return Result.error("密码不能为空");
        }
        else if (user.getPassword1() == null || user.getPassword1().equals("")){
            return Result.error("确认密码不能为空");
        }
        else if (!user.getPassword().equals(user.getPassword1())){
            return Result.error("密码不一致");
        }
        else if (user.getCode() == null || user.getCode().equals("")){
            return Result.error("验证码不能为空");
        }
        else if (codeMap.get(user.getEmail())==null){
            return Result.error("验证码已过期");
        }
        else if (codeMap.get(user.getEmail()).equals(user.getCode())){
            codeMap.remove(user.getEmail());
            if (userService.register(user)){
                return Result.success();
            }
            else {
                return Result.error("注册失败");
            }
        }
        else {
            return Result.error("验证码错误");
        }
    }

    @GetMapping("getcode")
    public Result getCode(String email){
        logger.info("获取验证码:{}", email);
        StringBuilder code = new StringBuilder();
        for (int i = 0; i < 6; i++) {
            int random = (int) (Math.random() * 10);
            code.append(random);
        }
        if (EmailSender.sendCode(email, code.toString())){
            codeMap.put(email, code.toString());
            return Result.success();
        }else {
            return Result.error("验证码发送失败");
        }
    }
    @GetMapping("loginByToken")
    public Result loginByToken(HttpServletRequest request){
        String token;
        try {
            token = request.getHeader("LY-Authorization").replace("\"", "");
        }catch (NullPointerException e){
            return Result.error("未登录");
        }
        logger.info("用户登录:{}", token);

        if (!JwtUntil.verifyToken(token)){
            return Result.error("timeover");
        }

        Map<String, Claim> data = JwtUntil.decodeToken(token);

        logger.info("解码的JWT声明: {}", data);

        String userId = data.get("userId").asString();

        User user = userService.getUserById(userId);

        if (user == null){
            return Result.error("用户不存在");
        }else{
            return Result.success(user);
        }

    }
}
